package com.atguigu.gulimail.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> listWithTree() {
        //1条sql语句查询出全量的分类
        List<CategoryEntity> all = baseMapper.selectList(null);

        //对分类进行操作
        List<CategoryEntity> collect = all.stream().filter(parent -> parent.getParentCid()==0)
                .map((menu) -> {
                    //对子类进行分类
                    menu.setChildren(getChild(menu, all));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() != null ? menu1.getSort() : 0) - (menu2.getSort() != 0 ? menu2.getSort() : 0);
                })
                .collect(Collectors.toList());

        return collect;
    }


    private List<CategoryEntity> getChild(CategoryEntity root,List<CategoryEntity> all) {

        List<CategoryEntity> childList = all.stream().filter(entity -> entity.getParentCid() == root.getCatId())
                .map((menu) -> {
                    menu.setChildren(getChild(menu, all));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() != null ? menu1.getSort() : 0) - (menu2.getSort() != 0 ? menu2.getSort() : 0);
                })
                .collect(Collectors.toList());

        return childList;
    }

}